{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "digits = datasets.load_digits()\n",
    "X = digits.data\n",
    "y = digits.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best K =  3\n",
      "Best p =  4\n",
      "best_score =  0.9860917941585535\n",
      "Wall time: 49.5 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "best_score, best_p, best_k= 0,0,0\n",
    "\n",
    "for k in range(2,10):\n",
    "    for p in range(1,6):\n",
    "        knn_clf = KNeighborsClassifier(weights='distance', n_neighbors=k, p=p)\n",
    "        knn_clf.fit(X_train, y_train)\n",
    "        # 没有使用交叉验证, 这里用测试集去找最好的参数, 存在过拟合\n",
    "        score = knn_clf.score(X_test, y_test)\n",
    "        if score > best_score:\n",
    "            best_score, best_k, best_p = score, k, p\n",
    "\n",
    "print('Best K = ', best_k)\n",
    "print('Best p = ', best_p)\n",
    "print('best_score = ', best_score)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用交叉验证"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.98895028, 0.97777778, 0.96629213])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn_clf = KNeighborsClassifier()\n",
    "cross_val_score(knn_clf, X_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 使用交叉验证调参"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best K =  2\n",
      "Best p =  2\n",
      "best_score =  0.9823599874006478\n",
      "Wall time: 48.8 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "best_score, best_p, best_k= 0,0,0\n",
    "\n",
    "# 这里的两层循环实际上是在干 grid_search \n",
    "for k in range(2,10):\n",
    "    for p in range(1,6):\n",
    "        knn_clf = KNeighborsClassifier(weights='distance', n_neighbors=k, p=p)\n",
    "#         knn_clf.fit(X_train, y_train)\n",
    "#         score = knn_clf.score(X_test, y_test)\n",
    "# 这里用训练集做交叉验证, 找到最佳参数, 耗时上没啥变化, 但是减小了过拟合的程度\n",
    "        scores = cross_val_score(knn_clf, X_train, y_train)\n",
    "        score = np.mean(scores)\n",
    "        if score > best_score:\n",
    "            best_score, best_k, best_p = score, k, p\n",
    "\n",
    "print('Best K = ', best_k)\n",
    "print('Best p = ', best_p)\n",
    "print('best_score = ', best_score)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_knn_clf = KNeighborsClassifier(weights='distance', n_neighbors=2, p=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.980528511821975"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "best_knn_clf.fit(X_train, y_train)\n",
    "best_knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 回顾网格搜索"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fitting 3 folds for each of 45 candidates, totalling 135 fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=1)]: Done 135 out of 135 | elapsed:  2.7min finished\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "GridSearchCV(cv=None, error_score='raise',\n",
       "       estimator=KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n",
       "           metric_params=None, n_jobs=1, n_neighbors=9, p=5,\n",
       "           weights='distance'),\n",
       "       fit_params=None, iid=True, n_jobs=1,\n",
       "       param_grid=[{'weights': ['distance'], 'n_neighbors': [2, 3, 4, 5, 6, 7, 8, 9, 10], 'p': [1, 2, 3, 4, 5]}],\n",
       "       pre_dispatch='2*n_jobs', refit=True, return_train_score='warn',\n",
       "       scoring=None, verbose=1)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "param_grid = [\n",
    "    {\n",
    "        'weights':['distance'],\n",
    "        'n_neighbors':[i for i in range(2,11)],\n",
    "        'p':[i for i in range(1,6)]\n",
    "    }\n",
    "]\n",
    "\n",
    "# GridSearch() 里面的参数 cv=3 可以设置fold个数, 默认是 3\n",
    "grid_search = GridSearchCV(knn_clf, param_grid, verbose=1)\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9823747680890538"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_search.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'n_neighbors': 2, 'p': 2, 'weights': 'distance'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_search.best_params_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.980528511821975"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "best_knn_clf = grid_search.best_estimator_\n",
    "best_knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.42 s ± 37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "%timeit cross_val_score(knn_clf, X_train, y_train, cv=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## K-folds cross validation \n",
    "* 缺点: 每次训练k个模型, 相当于整体性能慢了k倍\n",
    "\n",
    "* 优点: 找到的参数值得信赖\n",
    "\n",
    "极端情况下, k-folds cross validation方法可以变成 留一法 LOO-CV\n",
    "\n",
    "把训练数据集(共m个样本)分成m份, 用m-1份去训练, 用1份去评估, Leave-One-Out Cross Validation\n",
    "\n",
    "LOO-CV 完全不受随机的影响, 最接近模型真正的性能指标\n",
    "* 缺点: 计算量巨大"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
